var gestionClass = {
	win: null,
	layout: null,
	form: null,
	grid: null,
	actionBar: null,	
	widgetWin: function(){
        var me = this,
            windows = new dhtmlXWindows();

        me.win = windows.createWindow('window_1', 0, 0, 500, 200);
        me.win.setIcon('icon_09.png');
        me.win.setText('Gestión');
		me.win.button('park').hide();
		me.win.button('minmax1').hide();
		me.win.denyResize();
		me.win.setModal(1);
		me.win.centerOnScreen();

        widgetBar(this.win,1);
		me.layout = me.win.attachLayout('2U');
	},	
	widgetGrid: function(){	
		var me = this,
            panel = me.layout.cells('a');

		panel.hideHeader();
		panel.fixSize(true, true);

        me.statusGrid = panel.attachStatusBar();

		me.grid = panel.attachGrid();		
		me.grid.setImagePath(mainPath+'dhtmlx/imgs/');
		me.grid.setHeader(["ID","Gestión","Estado"],null,["","text-align:center","text-align:center"]);
		me.grid.setColTypes("ro,ro,ra");
		me.grid.setColAlign("right,center,center");
		me.grid.setInitWidths("30,*,73");
		me.grid.init();
        me.grid.setColumnColor("#E5E5E5");
		me.grid.load(mainPath+"index.php/gestion/grid_data", function(){
			me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
		},"json");
	},
    onClickStatusGrid: function(){
        var me = this,
            id;

        me.grid.attachEvent("onCheck", function(rId){
            id = me.grid.cells(rId,0).getValue();
            me.form.send(mainPath+'index.php/gestion/edit_data?id='+id+'&ges_status=1', function(loader, response){
                if(response == true){
                    me.grid.clearSelection();
                }
                else
                    dhtmlx.alert({
                        text: response
                    });
            });
        });
    },
	widgetForm: function(){
		var me = this,
            str,
            panel = me.layout.cells('b');

		panel.hideHeader();
		str = [
			{ type:"settings" , labelWidth:80, inputWidth:250, position:"absolute"  },
			{ type:"input" , name:"ges_gestion", label:"Gestión", labelAlign:"right", validate:"NotEmpty,ValidNumeric", inputWidth:75, labelLeft:30, labelTop:35, inputLeft:110, inputTop:35 },
			{ type:"button" , name:"btn_edit", label:"Button", value:"Modificar", width:"75", inputWidth:75, inputLeft:42, inputTop:60  },
			{ type:"button" , name:"btn_save", label:"Button", value:"Guardar", width:"75", inputWidth:75, inputLeft:125, inputTop:60  }
		];
		me.form = panel.attachForm(str);
		me.form.lock();
	},
    onEventForm: function(){
        var me = this;

        me.form.attachEvent("onButtonClick", function(name) {
            switch(name){
                case 'btn_save':
                    me.onClickButtonSaveData();
                break;
                case 'btn_edit':
                    me.onClickButtonEditData();
                break;
            }
        });
    },
    onClickButtonSaveData: function(){
        var me = this,
            auxFind,
            valCell,
            data = me.form.getFormData();

        if(me.form.validate()){
            auxFind = me.grid.findCell(data.ges_gestion,1);
            valCell = (auxFind != '')?me.grid.cells(auxFind[0][0],auxFind[0][1]).getValue():null;
            if (valCell != data.ges_gestion){
                me.form.send(mainPath+'index.php/gestion/save_data', function(loader, response) {
                    if(response > 0){
                        var id = me.grid.uid();
                        me.grid.addRow(id, [response,data.ges_gestion,1]);
                        me.grid.selectRowById(id);
                        me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                        me.form.clear();
                        me.form.lock();
                        actionBar.enableItem('btn_new');
                    }
                    else
                        dhtmlx.alert({
                            text: response
                        });
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, ya existe la gestion: '"+valCell.toUpperCase()+"', ingrese otro."
                });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    onClickButtonEditData: function(){
        var me = this,
            data,
            auxFind,
            valCell,
            rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();

        if(me.form.validate()){
            data = me.form.getFormData();
            auxFind = me.grid.findCell(data.ges_gestion,1);
            valCell = (auxFind != '')?me.grid.cells(auxFind[0][0],auxFind[0][1]).getValue():null;
            if (valCell != data.ges_gestion){
                me.form.send(mainPath+'index.php/gestion/edit_data?id='+rowId, function(loader, response){
                    if(response == true){
                        me.grid.cells(rowId,1).setValue(data.ges_gestion);
                        me.grid.clearSelection();
                        me.form.lock();
                        me.form.clear();
                    }
                    else
                        dhtmlx.alert({
                            text: response
                        });
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, ya existe el codigo '"+valCell.toUpperCase()+"', ingrese otro."
                });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    onEventActionToolBar: function(){
        var me = this;

        actionBar.attachEvent("onClick", function(itemId){
            switch(itemId){
                case 'btn_new':
                    me.onClickButtonNew(itemId);
                    break;
                case 'btn_edit':
                    me.onClickButtonEdit();
                    break;
                case 'btn_erase':
                    me.onClickButtonErase();
                    break;
                case 'btn_clear':
                    me.onClickButtonClear();
                    break;
            }
        });
    },
    onClickButtonNew: function(btnId){
        var me = this;

        actionBar.disableItem(btnId);
        me.form.unlock();
        me.form.setItemFocus('ges_gestion');
        me.form.disableItem('btn_edit');
        me.form.enableItem('btn_save');
    },
    onClickButtonEdit: function(){
        var me = this,
            id;

        id = me.grid.getSelectedRowId();
        if(id != null){
            me.form.unlock();
            me.form.disableItem('btn_save');
            me.form.enableItem('btn_edit');
            me.form.setItemValue('ges_gestion', me.grid.cells(id,1).getValue());
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder editar."
            });
    },
    onClickButtonErase: function(){
        var me = this,
            rowId;

        if(me.grid.getSelectedRowId() != null){
            rowId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
            dhtmlx.confirm({
                text:"¿Esta seguro que quieres eliminar el Ítem?",
                callback: function(status){
                    if(status == true){
                        if(me.grid.cells(me.grid.getSelectedRowId(),2).getValue() != 1){
                            me.form.send(mainPath+'index.php/gestion/erase_data?id='+rowId, function(loader, response){
                                if(response == true){
                                    me.grid.deleteSelectedRows();
                                    me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                                }
                                else
                                    dhtmlx.alert({
                                        text: response
                                    });
                            });
                        }
                        else
                            dhtmlx.alert({
                                text:"No se puede eliminar porque la gestión esta activa."
                            });
                    }
                }
            });
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder eliminar."
            });
    },
    onClickButtonClear: function(){
        var me = this;

        me.form.lock();
        me.form.clear();
        me.form.setItemFocus('btn_new');
        actionBar.enableItem('btn_new');
        me.grid.clearSelection();
    },
	widgetMain: function(){
        var me = gestionClass;

		me.widgetWin();
		me.widgetGrid();
        me.onClickStatusGrid();
		me.widgetForm();
        me.onEventForm();
        me.onEventActionToolBar();
	}
 };